import React, { useEffect, useMemo, useState } from "react";
import cls from "@/styles/pages/Schedule.module.scss";
import { useEvents } from "@/api/events";
import { FullMedCalendar } from "@/feature/FullMedCalendar/FullMedCalendar";
import { EventSourceInput } from "@fullcalendar/core";
import { useUserMe } from "@/store/auth";
import { convertEventTime, EVENT_DATA } from "@/pages/gantt/helpers";
import { Button } from "@/ui/Button/Button";
import moment from "moment/moment";
import { getPrediction } from "@/api/prediction";
import { CreateEvent } from "@/feature/CreateEvent/CreateEvent";
import { getMonthIdByStatus } from "@/feature/NewEventsTable/helper";

const mapper: Record<string, string> = {
  approved: "Утвержденное расписание",
  not_approved: "Не утвержденное расписание",
  temporary: "Временное расписание",
};

const Schedule = () => {
  const { userMe } = useUserMe();

  const [monthOffset, setMonthOffset] = useState(-4);
  const [monthId, setMonthId] = useState(1);
  const [modalOpen, setModalOpen] = useState(false);
  const [status, setStatus] = useState("not_approved");
  const [createLoading, setCreateLoading] = useState(false);

  useEffect(() => {
    const currMonth = moment().add(monthOffset, "month").get("month");
    const currYear = moment().add(monthOffset, "month").get("year");
    getPrediction(
      new URLSearchParams({
        month: String(currMonth + 1),
        year: String(currYear),
      })
    ).then((res) => {
      const m = getMonthIdByStatus(res.results);
      if (!m) return;
      setMonthId(m.id);
      setStatus(m.status);
    });
  }, [monthOffset, createLoading]);

  const eventParams = useMemo(() => {
    return new URLSearchParams({
      month: String(monthId),
      limit: "1000",
      user: String(userMe.id),
    });
  }, [userMe, monthId, createLoading]);

  const [, eventsData, specIsLoading] = useEvents(eventParams);

  const eventsScheduler = useMemo<EventSourceInput>(() => {
    return eventsData
      ? eventsData.map((item) => {
          return {
            start: convertEventTime(item),
            end: convertEventTime(item, true),
            title: EVENT_DATA[item.kind].title,
            backgroundColor: EVENT_DATA[item.kind].backgroundColor,
          };
        })
      : [];
  }, [eventsData]);

  return (
    <div className="page-wrapper">
      <div className={cls.header}>
        <div className={cls.title}>
          Статус расписания на этот месяц: {mapper[status]}
        </div>
        <div className={cls.btns}>
          <Button onClick={() => setModalOpen(true)}>Создать событие</Button>
          <div className={cls.monthBtns}>
            <Button onClick={() => setMonthOffset((p) => p - 1)}>
              Предыдущий месяц
            </Button>
            <Button onClick={() => setMonthOffset((p) => p + 1)}>
              Следующий месяц
            </Button>
          </div>
        </div>
        <FullMedCalendar events={eventsScheduler} monthOffset={monthOffset} />
      </div>
      <CreateEvent
        modalOpen={modalOpen}
        setModalOpen={setModalOpen}
        isLoading={createLoading}
        setIsLoading={setCreateLoading}
      />
    </div>
  );
};

export default Schedule;
